package edu.umassd.visual.util;

import java.io.BufferedReader;
import java.io.IOException;
import java.nio.charset.Charset;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.regex.Matcher;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import edu.umassd.raddacl.Observation;
import edu.umassd.raddacl.util.Constants;
import edu.umassd.visual.DataPoints;

@Component
public class ClusterFileSystemLoader
{
	@Autowired
	private DataPoints data;

	private Path path;

	public void loadClusters()
	{
		try
		{
			BufferedReader reader = Files.newBufferedReader(path,
					Charset.defaultCharset());

			List<Observation> list = new ArrayList<Observation>();

			String line = null;

			while ((line = reader.readLine()) != null)
			{
				if (line.equals("{"))
				{
					list = new ArrayList<>();
				}
				else if (line.equals("}"))
				{
					data.addCluster(new CopyOnWriteArrayList<>(list));
				}
				else
				{
					ObservationImpl obs = new ObservationImpl();
					Matcher matcher = Constants.CSV_OBSERVATION.matcher(line);

					while (matcher.find())
					{
						obs.add(Double.valueOf(matcher.group(1)));
					}

					list.add(obs);
				}
			}

		}
		catch (IOException e)
		{
			e.printStackTrace();
		}
	}

	public void setLocation(Path p)
	{
		this.path = p;
	}

	private static class ObservationImpl extends ArrayList<Double> implements
			Observation
	{
		private static final long serialVersionUID = 60466673803691645L;
	}
}
